from googletrans import Translator
import re

#语言代码：https://py-googletrans.readthedocs.io/en/latest/  
#如果整体翻译字幕文件,会使得字幕中的数字行和时间戳改变，所以只获取需要翻译的行，翻译后，再合并回去即可
def translate_srt(src_file,src_lang,src_encode,dest_file,dest_lang,dest_encode):
    subtitles = []
    #正则表达式匹配
    regex_number = r"(\d+)"
    regex_timerange =  r"(\d+):(\d+):(\d+),(\d+)(\s(0,1)\-(1-2))>(\s(0,1))(\d+):(\d+):(\d+),(\d+)"
    #读取所有行到subtitles中
    with open(src_file,"r",encoding=src_encode) as sf:
        subtitles.extend(sf.read().splitlines())
    #提取需要翻译的行
    transLines = []
    for line in subtitles:
        matchNum = re.match(regex_number, line)
        matchTime = re.match(regex_timerange, line)
        if not matchNum and  not matchTime and len(line) > 0 :
            transLines.append(line)  
    # 创建翻译对象
    #translate_string  = json.dumps(transLines,ensure_ascii=False)
    translate_string  = "\n".join(transLines)
    translator = Translator()
    translated_data = translator.translate(translate_string,src=src_lang, dest=dest_lang)   
    #把翻译后的数据替换到原来的翻译行中
    transedLines = translated_data.text.splitlines()
    i=0
    j=0
    for line in subtitles:        
        matchNum = re.match(regex_number, line)
        matchTime = re.match(regex_timerange, line)
        if not matchNum and  not matchTime and len(line) > 0 :
            subtitles[i] = transedLines[j]
            j = j+1
        i = i + 1  

    with open(dest_file,"w",encoding=dest_encode) as df:
        df.write("\n".join(subtitles))    